# -*- coding: utf-8 -*-

import requests,json,os,urllib,string,sys
import scrapy
from zuqiu.items import ZuqiuItem
from zuqiu.sqlHelper import *

reload(sys)
sys.setdefaultencoding('utf8')

class Win007Spider(scrapy.Spider):
    name = 'win007'
    allowed_domains = ['win007.com']
    handle_httpstatus_list = [301,403,404]
    DEFAULT_REQUEST_HEADERS={
        "Accept":"*/*",
        "Accept-Encoding":"gzip, deflate",
        "Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8",
        "Connection":"keep-alive",
        "Cookie":"UM_distinctid=1628ec7423447d-0c56a4debff1f7-4323461-1fa400-1628ec74235aad; CNZZDATA1261430177=1058722099-1522812190-null%7C1522812190",
        "Host":"zq.win007.com",
        "Referer":"http://zq.win007.com/cn/team/CTeamSche/1718.html",
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    }
    offset=1
    url='http://zq.win007.com/jsData/teamInfo/teamDetail/tdl'
    start_urls = [url+str(offset)+'.js?version=2018040411']
    def parse(self, response):
#        print '---'
        if response.status==404 or response.status==301 or response.status==403:
            print self.url+str(self.offset)+'------页面不存在'
        ct=response.body
        print ct
        return
        if self.save_data(en,cn,big):
            self.save_img(url,en)

        if self.offset < 90623:
            self.offset += 1
        print self.url+str(self.offset)
        yield scrapy.Request(self.url+str(self.offset)+'&lang=cn', callback = self.parse)

    def save_data(self,en,cn,big):
        if sqlHelper.selectOne("select id from team where en=%s and cn=%s",(en,cn)):
            sqlHelper.update("update team set big=%s where en=%s",(big,en))
        else:
            sqlHelper.update("insert into team(cn,en,logo,big) values(%s,%s,%s,%s)",(cn,en,en,big))
        return True
    
    def save_img(self,img_url,file_name,file_path='img'):
        img_url=img_url.replace('\/','/')
        try:
            if not os.path.exists(file_path):
                print '文件夹',file_path,'不存在，重新建立'
                #os.mkdir(file_path)
                os.makedirs(file_path)
            #获得图片后缀
            file_suffix = os.path.splitext(img_url)[1]
            #拼接图片名（包含路径）
            filename = '{}{}{}{}'.format(file_path,os.sep,file_name,file_suffix)
            filename=filename.replace('.com','_com')
            if string.find(filename,'.')==-1:
                filename=filename+'.png'
            if string.find(filename,'?')!=-1:
                filename=filename[0:len(filename)-4]
#       m下载图片，并保存到文件夹中
            urllib.urlretrieve(img_url,filename=filename)
        except IOError as e:
            print '文件操作失败',e
        except Exception as e:
            print '错误 ：',e

